package com.xxxx.comment.config;

import com.xxxx.comment.interceptor.LoginInterceptor;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


/**
 * @author lzf
 * @date 2023/7/9 18:29:53
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer
{
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        registry.addInterceptor(new LoginInterceptor(stringRedisTemplate))
                .addPathPatterns("/**") // 默认拦截所有路径
                // 不拦截的路径
                .excludePathPatterns("/user/code", "/user/login",
                        "/shop/**", "upload/**", "/voucher/**",
                        "/doc.html", "/webjars/**", "/swagger-resources", "/v2/api-docs")
                // 拦截器的生效顺序，数字越小，拦截器的preHandle方法执行顺序越靠前
                // 没有配置order的话默认按照使用registry.addInterceptor添加的顺序
                // 如果有多个拦截器的order相同，则按照addInterceptor的顺序执行
                .order(1);
    }

    /**
     * 跨域请求的配置
     *
     * @param registry 跨域服务的注册器
     */
    @Override
    public void addCorsMappings(CorsRegistry registry)
    {
        registry
                // 访问任何路径该配置都生效
                .addMapping("/**")
                // 允许的请求源,可以配置只允许本地请求.allowedOrigins("http://localhost:8080")
                .allowedOrigins("*")
                // 允许的请求方式
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowCredentials(false)
                .maxAge(60 * 60 * 24);
    }
}
